package util

import (
	"file-server/util"
	"fmt"
	"github.com/emirpasic/gods/maps/treemap"
	"github.com/emirpasic/gods/utils"
	"reflect"
)

func AuthHeader(accessToken interface{}, ts interface{}) string {
	temp := utils.ToString(accessToken) + utils.ToString(ts)
	fmt.Println("TOKEN拼接：", temp)
	return util.SHA256Str(temp)
}

func AuthSign(param *treemap.Map, accessToken string) string {
	iter := param.Iterator()

	temp := ""

	for iter.Next() {
		key := iter.Key()
		val := iter.Value()
		if validKey(key) && validValue(val) {
			temp += "&" + utils.ToString(key) + "=" + utils.ToString(val)
		}
	}

	temp += "&" + utils.ToString(accessToken)
	temp = temp[1:len(temp)]
	fmt.Println("参数拼接：", temp)
	return util.SHA256Str(temp)
}

var mapType = reflect.TypeOf(make(map[string]interface{}))

func AuthSignCommon(param *map[string]interface{}, accessToken string) string {
	treeMap := treemap.NewWithStringComparator()

	for k, v := range *param {
		if reflect.TypeOf(v) == mapType {
			continue
		}
		treeMap.Put(k, v)
	}

	return AuthSign(treeMap, accessToken)
}

func validKey(key interface{}) bool {
	return "sign" != key && "accessToken" != key
}

func validValue(val interface{}) bool {
	if val == nil || "" == val {
		return false
	}
	return true
}
